<template>
  <div class="share-access-page">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 密码验证界面 -->
    <div v-else-if="!accessGranted && shareInfo" class="password-verification">
      <div class="share-card">
        <!-- 文件信息预览 -->
        <div class="file-preview-card">
          <div class="file-icon">
            <el-icon size="48"><Document /></el-icon>
          </div>
          <div class="file-details">
            <h2 class="file-name">{{ shareInfo.fileName }}</h2>
            <div class="file-meta">
              <span>{{ t('share.access.fileSize') }}: {{ formatFileSize(shareInfo.fileSize || 0) }}</span>
              <span>{{ t('share.access.sharedBy') }}: {{ shareInfo.sharerName }}</span>
            </div>
          </div>
        </div>

        <!-- 分享备注信息 -->
        <div v-if="shareInfo.description" class="share-description">
          <el-divider />
          <div class="description-content">
            <div class="description-label">
              <el-icon><InfoFilled /></el-icon>
              {{ t('share.access.shareDescription') }}
            </div>
            <div class="description-text">{{ shareInfo.description }}</div>
          </div>
        </div>

        <!-- 密码输入 -->
        <div v-if="shareInfo.shareType === 'PASSWORD'" class="password-section">
          <el-divider />
          <div class="password-form">
            <h3>
              <el-icon class="lock-icon"><Lock /></el-icon>
              {{ t('share.access.enterPassword') }}
            </h3>
            <el-form @submit.prevent="verifyAccess">
              <el-form-item>
                <el-input
                  v-model="password"
                  type="password"
                  :placeholder="t('share.access.passwordPlaceholder')"
                  show-password
                  @keyup.enter="verifyAccess"
                  :disabled="verifying"
                  size="large"
                  class="password-input"
                >
                  <template #prefix>
                    <el-icon><Key /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="verifyAccess"
                  :loading="verifying"
                  size="large"
                  class="access-btn"
                >
                  {{ verifying ? t('share.access.verifying') : t('share.access.verifyAccess') }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 公开分享直接访问 -->
        <div v-else class="public-access">
          <el-divider />
          <el-button
            type="primary"
            @click="verifyAccess"
            :loading="verifying"
            style="width: 100%"
          >
            {{ t('share.access.previewFile') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 文件内容展示 -->
    <div v-else-if="accessGranted && fileContent" class="file-content">
      <div class="content-header">
        <div class="file-info">
          <h1>{{ fileContent.fileInfo.fileName }}</h1>
          <div class="file-meta">
            <span>{{ t('share.access.fileSize') }}: {{ formatFileSize(fileContent.fileInfo.fileSize || 0) }}</span>
            <span>{{ t('share.access.sharedBy') }}: {{ fileContent.fileInfo.sharerName }}</span>
            <span>{{ t('common.type') }}: {{ fileContent.fileInfo.mimeType || t('common.unknown') }}</span>
          </div>
        </div>

        <div class="action-buttons">
          <el-button
            v-if="fileContent.permissions.allowDownload"
            @click="downloadFile"
            :loading="downloading"
            type="primary"
          >
            <el-icon><Download /></el-icon>
            {{ downloading ? t('share.access.downloading') : t('share.access.downloadFile') }}
          </el-button>
        </div>
      </div>

      <!-- 文件预览区域 -->
      <div v-if="fileContent.permissions.allowPreview" class="file-preview-area">
        <div class="preview-container">
          <!-- 图片预览 -->
          <div v-if="isImageFile" class="image-preview">
            <img
              :src="fileContent.previewUrl"
              :alt="fileContent.fileInfo.fileName"
              @error="handlePreviewError"
            />
          </div>

          <!-- PDF文件信息展示（替代预览） -->
          <div v-else-if="isPdfFile" class="pdf-info-display">
            <div class="file-info-card">
              <div class="file-icon-wrapper">
                <el-icon class="pdf-icon"><Document /></el-icon>
              </div>
              <div class="file-details">
                <h3>{{ fileContent.fileInfo.fileName }}</h3>
                <div class="file-properties">
                  <div class="property-row">
                    <span class="label">文件大小：</span>
                    <span class="value">{{ formatFileSize(fileContent.fileInfo.fileSize || 0) }}</span>
                  </div>
                  <div class="property-row">
                    <span class="label">文件类型：</span>
                    <span class="value">PDF 文档</span>
                  </div>
                </div>
                <div class="file-note">
                  <el-icon><InfoFilled /></el-icon>
                  PDF 文件请下载后使用 PDF 阅读器查看
                </div>
              </div>
            </div>
          </div>

          <!-- 视频预览 -->
          <div v-else-if="isVideoFile" class="video-preview">
            <video
              :src="fileContent.previewUrl"
              controls
              width="100%"
              @error="handlePreviewError"
            >
              您的浏览器不支持视频播放
            </video>
          </div>

          <!-- 音频预览 -->
          <div v-else-if="isAudioFile" class="audio-preview">
            <audio
              :src="fileContent.previewUrl"
              controls
              @error="handlePreviewError"
            >
              您的浏览器不支持音频播放
            </audio>
          </div>

          <!-- 文本文件预览 -->
          <div v-else-if="isTextFile" class="text-preview">
            <pre>{{ textContent }}</pre>
          </div>

          <!-- 不支持预览的文件 -->
          <div v-else class="unsupported-preview">
            <el-result
              icon="info"
              title="无法预览此文件"
              sub-title="该文件类型不支持在线预览，请下载后查看"
            >
              <template #extra>
                <el-button
                  v-if="fileContent.permissions.allowDownload"
                  type="primary"
                  @click="downloadFile"
                >
                  下载文件
                </el-button>
              </template>
            </el-result>
          </div>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="errorMessage" class="error-state">
      <el-result
        icon="warning"
        title="访问失败"
        :sub-title="errorMessage"
      >
        <template #extra>
          <el-button @click="$router.push('/')">返回首页</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document, Download, Lock, Key, InfoFilled } from '@element-plus/icons-vue'
import * as shareApi from '@/api/modules/share'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const verifying = ref(false)
const downloading = ref(false)
const shareInfo = ref<shareApi.ShareInfoResponse | null>(null)
const fileContent = ref<shareApi.ShareAccessResponse | null>(null)
const accessGranted = ref(false)
const password = ref('')
const errorMessage = ref('')
const textContent = ref('')

// 获取分享码
const shareCode = route.params.shareCode as string

// 文件类型判断
const isImageFile = computed(() => {
  return fileContent.value?.fileInfo?.mimeType?.startsWith('image/') || false
})

const isPdfFile = computed(() => {
  return fileContent.value?.fileInfo?.mimeType === 'application/pdf' || false
})

const isVideoFile = computed(() => {
  return fileContent.value?.fileInfo?.mimeType?.startsWith('video/') || false
})

const isAudioFile = computed(() => {
  return fileContent.value?.fileInfo?.mimeType?.startsWith('audio/') || false
})

const isTextFile = computed(() => {
  const mimeType = fileContent.value?.fileInfo?.mimeType || ''
  return mimeType.startsWith('text/') ||
         mimeType === 'application/json' ||
         mimeType === 'application/xml'
})

// 页面加载时获取分享信息
onMounted(async () => {
  if (!shareCode) {
    errorMessage.value = '分享链接无效'
    loading.value = false
    return
  }

  try {
    const response = await shareApi.getShareInfo(shareCode)
    shareInfo.value = response.data

    // 如果是公开分享，直接尝试访问
    if (shareInfo.value.shareType === 'PUBLIC') {
      await verifyAccess()
    }
  } catch (error: any) {
    console.error('Failed to get share info:', error)

    // 根据错误类型显示友好提示
    if (error.response) {
      const status = error.response.status
      const data = error.response.data

      if (status === 400) {
        // 后端返回的业务错误
        errorMessage.value = data?.message || '分享链接已失效'
      } else if (status === 404) {
        errorMessage.value = '分享不存在或已被删除'
      } else if (status === 403) {
        errorMessage.value = '无权限访问此分享'
      } else {
        errorMessage.value = '分享服务暂时不可用，请稍后再试'
      }
    } else if (error.request) {
      errorMessage.value = '网络连接失败，请检查网络后重试'
    } else {
      errorMessage.value = '分享链接无效或已失效'
    }
  } finally {
    loading.value = false
  }
})

// 验证访问权限
const verifyAccess = async () => {
  if (!shareInfo.value) return

  try {
    verifying.value = true
    
    const accessRequest: shareApi.ShareAccessRequest = {
      action: 'VIEW'
    }
    
    // 如果是密码保护，添加密码
    if (shareInfo.value.shareType === 'PASSWORD') {
      if (!password.value.trim()) {
        ElMessage.warning(t('share.access.passwordPlaceholder'))
        return
      }
      accessRequest.password = password.value
    }

    const response = await shareApi.accessShare(shareCode, accessRequest)
    
    if (response.data.allowed) {
      fileContent.value = response.data
      accessGranted.value = true
      ElMessage.success(t('share.messages.accessSuccess'))
    } else {
      errorMessage.value = response.data.errorMessage || t('share.access.accessDenied')
    }
    
  } catch (error: any) {
    console.error('Access verification failed:', error)

    // 根据错误类型显示友好提示
    if (error.response) {
      const status = error.response.status
      const data = error.response.data

      if (status === 400) {
        const message = data?.message || t('share.messages.accessFailed')
        if (message.includes('密码错误')) {
          ElMessage.error(t('share.access.passwordError'))
        } else if (message.includes('已过期')) {
          errorMessage.value = t('share.access.shareExpired')
        } else if (message.includes('已禁用')) {
          errorMessage.value = t('share.messages.shareDisabled')
        } else if (message.includes('访问次数')) {
          errorMessage.value = t('share.messages.accessLimitReached')
        } else {
          ElMessage.error(message)
        }
      } else {
        ElMessage.error(t('share.messages.accessFailed'))
      }
    } else {
      ElMessage.error(t('common.networkError'))
    }
  } finally {
    verifying.value = false
  }
}

// 下载文件
const downloadFile = async () => {
  if (!fileContent.value?.accessToken) return

  try {
    downloading.value = true
    
    const response = await shareApi.downloadSharedFile(shareCode, fileContent.value.accessToken)
    
    // 创建下载链接
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileContent.value.fileInfo?.fileName || 'download'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success(t('share.access.downloadSuccess'))

  } catch (error: any) {
    console.error('Download failed:', error)
    ElMessage.error(t('share.access.downloadFailed') + ': ' + (error.message || t('common.unknownError')))
  } finally {
    downloading.value = false
  }
}

// 预览错误处理
const handlePreviewError = () => {
  ElMessage.error(t('share.access.previewNotSupported'))
}

// 格式化文件大小
const formatFileSize = shareApi.formatFileSize
</script>

<style scoped lang="scss">
.share-access-page {
  min-height: 100vh;
  background: #f8fafc;
  padding: 20px;
}

.loading-container {
  max-width: 600px;
  margin: 50px auto;
  padding: 30px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
}

.password-verification {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.share-card {
  width: 100%;
  max-width: 520px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
  overflow: hidden;
}

.file-preview-card {
  padding: 32px;
  text-align: center;
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
  color: white;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(147, 51, 234, 0.1) 100%);
  }

  > * {
    position: relative;
    z-index: 1;
  }

  .file-icon {
    margin-bottom: 16px;
    opacity: 0.9;
  }

  .file-name {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 12px 0;
    word-break: break-all;
  }

  .file-meta {
    font-size: 14px;
    opacity: 0.8;
    
    span {
      margin-right: 16px;
    }
  }
}

.password-section, .public-access {
  padding: 30px;

  h3 {
    text-align: center;
    margin-bottom: 20px;
    color: #303133;
  }
}

.file-content {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.content-header {
  padding: 24px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .file-info {
    flex: 1;

    h1 {
      font-size: 28px;
      margin: 0 0 12px 0;
      color: #303133;
      word-break: break-all;
    }

    .file-meta {
      color: #909399;
      font-size: 14px;

      span {
        margin-right: 20px;
      }
    }
  }

  .action-buttons {
    flex-shrink: 0;
    margin-left: 20px;
  }
}

.file-preview-area {
  padding: 24px;
  min-height: 500px;
  background: #fafafa;
}

.preview-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-preview {
  text-align: center;
  padding: 20px;

  img {
    max-width: 100%;
    max-height: 600px;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
}

.pdf-preview {
  iframe {
    border: none;
    border-radius: 4px;
  }
}

.video-preview {
  padding: 20px;
  text-align: center;

  video {
    max-width: 100%;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
}

.audio-preview {
  padding: 40px;
  text-align: center;

  audio {
    width: 100%;
    max-width: 500px;
  }
}

.text-preview {
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;

  pre {
    background: #f8f9fa;
    padding: 16px;
    border-radius: 4px;
    font-family: 'Courier New', monospace;
    font-size: 14px;
    line-height: 1.5;
    white-space: pre-wrap;
    word-wrap: break-word;
  }
}

.unsupported-preview {
  padding: 40px;
}

.error-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

@media (max-width: 768px) {
  .share-access-page {
    padding: 10px;
  }

  .content-header {
    flex-direction: column;
    align-items: stretch;

    .action-buttons {
      margin-left: 0;
      margin-top: 16px;
    }
  }

  .file-preview-card {
    padding: 20px;

    .file-name {
      font-size: 20px;
    }
  }
}

// 分享备注样式
.share-description {
  .description-content {
    padding: 16px 24px;
    background: #f8fafc;
    border-radius: 8px;
    margin: 0 24px;
  }

  .description-label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #475569;
    margin-bottom: 8px;
    font-size: 14px;
  }

  .description-text {
    color: #64748b;
    line-height: 1.6;
    font-size: 14px;
  }
}

// 密码输入样式优化
.password-section {
  .password-form {
    h3 {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #334155;
      font-size: 16px;
      font-weight: 600;

      .lock-icon {
        color: #64748b;
      }
    }
  }

  .password-input {
    :deep(.el-input__inner) {
      border-radius: 8px;
      border: 2px solid #e2e8f0;
      transition: all 0.2s;

      &:focus {
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
      }
    }
  }

  .access-btn {
    width: 100%;
    border-radius: 8px;
    height: 44px;
    font-weight: 600;
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border: none;

    &:hover {
      background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
    }
  }
}

// PDF信息展示样式
.pdf-info-display {
  padding: 40px;
  text-align: center;

  .file-info-card {
    max-width: 400px;
    margin: 0 auto;
    padding: 32px;
    background: #f8fafc;
    border-radius: 12px;
    border: 2px dashed #cbd5e1;
  }

  .file-icon-wrapper {
    margin-bottom: 20px;

    .pdf-icon {
      font-size: 64px;
      color: #dc2626;
    }
  }

  .file-details {
    h3 {
      margin: 0 0 16px 0;
      color: #1e293b;
      font-size: 18px;
      font-weight: 600;
    }
  }

  .file-properties {
    margin-bottom: 16px;

    .property-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      .label {
        color: #64748b;
        font-size: 14px;
      }

      .value {
        color: #334155;
        font-weight: 500;
        font-size: 14px;
      }
    }
  }

  .file-note {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: #64748b;
    font-size: 14px;
    padding: 12px;
    background: #e2e8f0;
    border-radius: 6px;
  }
}
</style>
